package com.boxing;

import com.boxing.bean.RespResult;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * ajax 的servlet
 */
@WebServlet(name = "LoginServletJson", value = "/LoginServletJson")
public class LoginServletJson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(LoginServletJson.class + " 执行了doGet方法");
        // 设置编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String psd = request.getParameter("psd");
        System.out.println("get收到的信息是 " + name +"  "+psd);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(LoginServletJson.class + "执行了doPost方法");

        // 设置编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String name = request.getParameter("name");
        String psd = request.getParameter("psd");
        System.out.println("收到的信息是 " + name +"  "+psd);
        // 需要检验用户名和密码是否合法
        Gson gson = new Gson();
        RespResult respResult = new RespResult();
        if ("张三".equals(name)){
            // 合法的
            respResult.setState(1);
            respResult.setMsg("登录成功");
            response.getWriter().print(gson.toJson(respResult));
        }else {
            respResult.setState(0);
            respResult.setMsg("登录失败");
            response.getWriter().print(gson.toJson(respResult));
        }
    }
}
